package com.gee.spring.boot.starter.opengemini.config;

import io.opengemini.client.api.Address;
import io.opengemini.client.api.AuthConfig;
import io.opengemini.client.api.AuthType;
import io.opengemini.client.jdk.OpenGeminiJdkClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.stream.Collectors;

import static com.gee.spring.boot.starter.opengemini.core.constant.StrConstant.COLON;

/**
 * @author gepengjun
 * @since 2024/4/30 10:42
 */
@Configuration
@ConditionalOnProperty(prefix = "spring.opengemini", name = "enable", matchIfMissing = true)
@EnableConfigurationProperties(OpengeminiProperties.class)
public class OpengeminiAutoConfiguration {

    @Autowired
    private OpengeminiProperties opengeminiProperties;

    @Bean
    public OpenGeminiJdkClient openGeminiJdkClient(){
        List<Address> addressList = opengeminiProperties.getServerUrlList().stream()
                .map(serverUrl -> {
                    String[] split = serverUrl.split(COLON);
                    return new Address(split[0], Integer.parseInt(split[1]));
                })
                .collect(Collectors.toList());
        io.opengemini.client.jdk.Configuration configuration = io.opengemini.client.jdk.Configuration.builder()
                .addresses(addressList)
                .authConfig(new AuthConfig(AuthType.PASSWORD, opengeminiProperties.getUsername(), opengeminiProperties.getPassword(), null))
                .connectTimeout(opengeminiProperties.getConnectTimeout())
                .timeout(opengeminiProperties.getTimeout())
                .build();
        return new OpenGeminiJdkClient(configuration);
    }

    @Bean
    public OpengeminiTemplate opengeminiTemplate(OpenGeminiJdkClient openGeminiJdkClient){
        return new OpengeminiTemplate(openGeminiJdkClient, opengeminiProperties);
    }

}
